package com.aigou.admin.aigouspringboot.interceptor;

import com.aigou.admin.aigouspringboot.entity.User;
import com.aigou.admin.aigouspringboot.result.Result;
import com.aigou.admin.aigouspringboot.utils.JSONUtils;
import com.aigou.admin.aigouspringboot.utils.JWTUtils;

import com.aigou.admin.aigouspringboot.utils.ResponseUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * jwt令牌校验的拦截器
 */
@Component
@Slf4j
public class JwtTokenAdminInterceptor implements HandlerInterceptor {


    /**
     * 校验jwt
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 解决跨域
        response.setHeader("Access-Control-Allow-Origin", request.getHeader("origin"));
        //该字段可选，是个布尔值，表示是否可以携带cookie
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT,DELETE");
        response.setHeader("Access-Control-Allow-Headers", "*");

        //如果是 OPTIONS 请求，让 OPTIONS 请求返回一个200状态码（解决获取不到token）
        if (HttpMethod.OPTIONS.toString().equals(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
            return false;
        }


        if (request.getRequestURI().contains("login")) {
            return true;
        }
        String token = request.getHeader("Authorization");
        System.out.println(token);
        if (!StringUtils.hasText(token)) {
            Result<Object> result = Result.error(900, "请求头token不存在");
            String resultJson = JSONUtils.toJSON(result);
            ResponseUtils.write(response, resultJson);

            return false;
        }
        // 验证token
        User user = JWTUtils.parseUserFromJWT(token);
        if (user == null) {
            Result<Object> result = Result.error(900, "请求头token不存在");
            String resultJson = JSONUtils.toJSON(result);
            ResponseUtils.write(response, resultJson);
            return false;
        }
        return true;
    }
}
